/**
 * @description 页面业务文件
*/
import { state } from '../../../service/stock/index.js'
import naveSer from '../../../service/action/nave.action.js'
import dicSer from '../../../service/action/dictionary.action.js'
import noteSer from '../../../service/action/note.action.js'
import { treer, funcer, parser } from '@daelui/dogjs/dist/components'
import { CACHE_TYPE } from '../../../service/components/ds'

export default {
  // 规则列表
  ruleList: [],
  // 环境规则列表
  ruleEnvList: [],
  // 笔记列表
  notesList: [],
  /**
   * @function 缓存环境数据
  */
  setEnvirmentCache (data) {
    let key = 'nave-env-setting-cache'
    let result = JSON.stringify(data)
    if (data.key === 'sessionStorage') {
      sessionStorage.setItem(key, result)
    } else if (data.key === 'localStorage') {
      localStorage.setItem(key, result)
    }
    localStorage.setItem('nave-env-setting-cache-key', data.key)
  },

  /**
   * @function 获取缓存环境数据
  */
  getEnvirmentCache () {
    let key = localStorage.getItem('nave-env-setting-cache-key')
    let storage = null
    if (key === 'sessionStorage') {
      storage = sessionStorage
    } else if (key === 'localStorage') {
      storage = localStorage
    }
    let data = null
    if (storage) {
      data = storage.getItem('nave-env-setting-cache')
    }
    if (data) {
      try {
        data = JSON.parse(data)
      } catch (e) {
        data = null
      }
    }

    return data
  },

  /**
   * @function 移除缓存环境数据
  */
  removeEnvirmentCache () {
    let key = 'nave-env-setting-cache'
    sessionStorage.removeItem(key)
    localStorage.removeItem(key)
    localStorage.removeItem('nave-env-setting-cache-key')
  },

  /**
   * @function 获取环境
  */
  getEnvirment () {
    return new Promise((resolve) => {
      // 环境缓存
      let cacheEnv = this.getEnvirmentCache()
      if (cacheEnv && cacheEnv.code) {
        resolve(cacheEnv.code)
        return true
      }
      // 查询全局环境
      dicSer.queryItem({
        cat: 'nave-env-setting'
      }, {cache: true}).then(res => {
        if (res.data && res.data.code) {
          resolve(res.data.code)
        }
      }).catch(() => {
        resolve('')
      })
    })
  },

  /**
   * @function 查询字典列表
   * @param {Object} params 参数对象
   * @return {Promise}
  */
  queryListByGroup () {
    let ruleEnvDefer = dicSer.queryList({
      cat: 'rule-env'
    }, {cache: true, cacheType: CACHE_TYPE.SESSION, buffer: true})
    // 环境一维数据带层级字符
    let envDefer = this.queryTreeEnv()
    let ruleDefer = dicSer.queryList({
      cat: 'nave-rule'
    }, {cache: true, cacheType: CACHE_TYPE.SESSION, buffer: true})
    // 环境树形数据
    let envLevelDefer = dicSer.queryTree({cat: 'nave-envirment'}, {cache: true, buffer: true})
    let envIdDefer = this.getEnvirment()
    return Promise.all([ruleEnvDefer, envDefer, ruleDefer, envLevelDefer, envIdDefer]).then(results => {
      let [r1, r2, r3, r4, r5] = results
      this.ruleList = r3?.data
      this.ruleEnvList = r1?.data
      this.envirmentList = r2
      let envLevelList = (r4?.data || {}).list
      envLevelList = Array.isArray(envLevelList) ? envLevelList : []
      this.envLevelList = envLevelList
      this.globalEnvirment = r5
      return {
        data: {
          ruleEnvList: r1?.data,
          envirmentList: r2,
          ruleList: r3?.data,
          envLevelList,
          envirment: r5
        }
      }
    }).catch(e => {
      return {data: {ruleEnvList: [], envirmentList: []}}
    })
  },

  /**
   * @function 获取节点地址
  */
  getEnvHref (node, envirmentList, globalEnvirment, settingEnv, useNode, max) {
    let href = node.href
    envirmentList = envirmentList || this.envirmentList
    globalEnvirment = globalEnvirment || this.globalEnvirment
    useNode = useNode || {}
    // 引用源页面
    let rNode = {}
    max = max || 1
    // 引用页面
    if (this.isResourcePage(node)) {
      (this.pageTree || []).forEach(item => {
        if (item.id === node.rid) {
          rNode = item
          if (max <= 30) {
            href = this.getEnvHref(item, envirmentList, globalEnvirment, settingEnv, node, max + 1) || href
          }
        }
      })
    } else if (this.isEnvirmentMatch(node)) { // 环境匹配
      useNode.hrefList = parser.toObject(useNode.hrefList)
      useNode.hrefList = Array.isArray(useNode.hrefList) ? useNode.hrefList : []
      node.hrefList = parser.toObject(node.hrefList)
      node.hrefList = Array.isArray(node.hrefList) ? node.hrefList : []
      let hrefList = [...node.hrefList, ...useNode.hrefList]
      let useHref = ''
      let setHref = ''
      let globalHref = ''
      hrefList.forEach(item => {
        if (item.envirment === useNode.envirment) {
          useHref = item.href
        } else if (item.envirment === settingEnv) {
          setHref = item.href
        } else if (item.envirment === globalEnvirment) {
          globalHref = item.href
        }
        href = useHref || setHref || globalHref || href
      })
    }
    // 环境列表
    let layout = parser.parse(node.layout) || ''
    let envIds = Array.isArray(layout.envList) ? layout.envList : String(layout.envList || '').split(',')
    envIds = envIds.filter(node => {
      return !!node
    })
    let layoutUsed = parser.parse(useNode.layout) || ''
    let envIdsUsed = Array.isArray(layoutUsed.envList) ? layoutUsed.envList : String(layoutUsed.envList || '').split(',')
    envIdsUsed = envIdsUsed.filter(node => {
      return !!node
    })
    envIds = envIdsUsed.length ? envIdsUsed : envIds
    // 指定环境
    href = this.resolveHref(href, envirmentList, useNode.envirment || settingEnv)
    // 当前环境
    href = this.resolveHref(href, envirmentList, useNode.envirment || node.envirment)
    // 全局环境对应的配置环境
    let childEnvId = ''
    let envLevelList = this.envLevelList || []
    envLevelList.forEach(item => {
      if (item.id === globalEnvirment) {
        childEnvId = item.id
        let children = item.children
        children = Array.isArray(children) ? children : []
        children.forEach(node => {
          if (envIds.indexOf(node.id) > -1) {
            childEnvId = node.id
          }
        })
      }
    })
    href = this.resolveHref(href, envirmentList, childEnvId)
    // 引用环境
    href = this.resolveHref(href, envirmentList, rNode.envirment)
    // 全局环境
    href = this.resolveHref(href, envirmentList, globalEnvirment)

    return href
  },

  /**
   * @function 解析地址
  */
  resolveHref (href, envirmentList, envirment) {
    // 环境列表
    let env = {}
    envirmentList = Array.isArray(envirmentList) ? envirmentList : []
    envirmentList.forEach(sec => {
      if (sec.id && sec.id === envirment) {
        env = sec
      }
    });
    // 环境规则替换
    (this.ruleEnvList || []).forEach((ruleEnv) => {
      if (href && env.id === ruleEnv.key) {
        let rule = this.ruleList.find(node => {
          return ruleEnv.code === node.id
        })
        if (rule) {
          href = String(href).replace(rule.key, ruleEnv.value)
        }
      }
    })

    return href
  },

  /**
   * @function 是否普通页面
  */
  isNormal (node) {
    let type = node.type
    let b = true
    state.pageTypeList.forEach(item => {
      if (
        item.id === type &&
        (state.pageTypeList.RESOURCE_PAGE === item.key || state.pageTypeList.ENVIRMENT_MATCH === item.key)
      ) {
        b = false
      }
    })
    return b
  },

  /**
   * @function 是否普通页面
  */
  isResourcePage (node) {
    let type = node.type
    let b = false
    state.pageTypeList.forEach(item => {
      if (item.id === type && state.pageTypeList.RESOURCE_PAGE === item.key) {
        b = true
      }
    })
    return b
  },

  /**
   * @function 是否普通页面
  */
  isEnvirmentMatch (node) {
    let type = node.type
    let b = false
    state.pageTypeList.forEach(item => {
      if (item.id === type && state.pageTypeList.ENVIRMENT_MATCH === item.key) {
        b = true
      }
    })
    return b
  },

  /**
   * @function 获取源页面
  */
  getOriginHref (node) {
    let href = node.href
    // 非普通页面
    if (!this.isNormal(node)) {
      (this.treeData || []).forEach(item => {
        if (item.id === node.rid) {
          href = item.href || href
        }
      })
    }
    return href
  },

  /**
   * @function 查询页面数据
  */
  queryTreeData () {
    // 查询页面数据
    return naveSer.queryTree({}, {cache: true}).then(res => {
      let list = (res?.data || {}).list
      list = Array.isArray(list) ? list : []
      let arr = [], pageTree = []
      treer.forEach(list, function (item, level) {
        arr.push({
          id: item.id,
          name: funcer.loop(level, ' - ') + item.name,
          href: item.href
        })
        pageTree.push(item)
      })
      this.treeData = arr
      this.pageTree = pageTree
      return arr
    })
  },

  /**
   * @function 查询环境树形数据
  */
  queryTreeEnv () {
    // 查询页面数据
    return dicSer.queryTreeEnv()
  },

  /**
   * @function 获取笔记
  */
  queryNotes (node) {
    node = node || {}
    //查询笔记列表
    return noteSer.queryListOptions({}, {cache: true, buffer: true}).then(res => {
      let data = res.data
      data = Array.isArray(data) ? data : []
      this.notesList = data
      return this.getNotes(node)
    })
  },

  /**
   * @function 获取笔记
  */
  getNotes (node) {
    node = node || {}
    let list = []
    String(node.notes = node.notes || '').split(',').forEach(item => {
      let note = this.notesList.find(note => note.id === item)
      if (note) {
        list.push(note)
      }
    })
    return list
  }
}
